import Vue from 'vue'
import Vuex from 'vuex'

import loginApi from "@/api/login.js"

// 1. 安装插件 vue的底层会执行 Vue.install
Vue.use(Vuex)

// import {
// 	ZIM
// } from 'zego-zim-miniprogram';

import ZIM from '@/common/ZIM-main-miniprogram/index.js';

// 2. 创建对象
const store = new Vuex.Store({
	state: {
		zim: null,
		userInfo: null,
		conversationList: [],

	},
	mutations: {
		set_zim(state, data) {
			state.zim = data
		},

		set_conversationList(state, data) {
			for (let item of data) {
				if (item.lastMessage) {
					let extendedData = JSON.parse(item.lastMessage.extendedData)
					if (extendedData.quiz_id) {
						state.zim.deleteConversation(item.conversationID, 0, {
							isAlsoDeleteServerConversation: true
						})
					}
				}
			}
			state.conversationList = data.sort((obj1, obj2) => {
				return obj2.orderKey - obj1.orderKey;
			})
		},

		// 更新会话列表，接受一个数组
		updata_ConversationList(state, infoList) {
			let conversationList = state.conversationList
			for (let item of infoList) {
				let is = false
				if (item.lastMessage) {
					let extendedData = JSON.parse(item.lastMessage.extendedData)
					if (extendedData.quiz_id) {
						state.zim.deleteConversation(item.conversationID, 0, {
							isAlsoDeleteServerConversation: true
						})
						continue;
					}
				}
				let num = 0
				for (let i = 0; i < conversationList.length; i++) {
					if (conversationList[i].conversationID == item.conversation.conversationID) {
						conversationList.splice(i, 1, item.conversation)
						is = true
					}
					num += item.conversation.unreadMessageCount
				}
				console.log('消息未读数', num)
				if (num > 0) {
					uni.showTabBarRedDot({
						index: 3
					})
				}else{
					uni.hideTabBarRedDot({
						index: 3
					})
				}
				if (!is) conversationList.push(item.conversation)

			}


			console.log('会话列表', conversationList)
			state.conversationList = conversationList.sort((obj1, obj2) => {
				return obj2.orderKey - obj1.orderKey;
			})

		},
	},
	actions: {
		createZIM(context) {
			return new Promise(async (resolve, reject) => {


				// 静态同步方法，创建 zim 实例，传入 AppID。
				// create 方法仅第一次调用时会创建 ZIM 实例，后续调用会返回 null。
				ZIM.create({
					appID: 1472263955,
					appSign: '0d8c26d495532eed3a1e56f4b2e3520e177cf176f0930e0fa3157104c43deaa0'
				});
				// 通过 getInstance 获取单实例，避免热更新导致 create 多次创建返回 null。
				let zim = ZIM.getInstance();
				context.commit('set_zim', zim)
				resolve(zim)

			})
		},
		ZIMLogin(context) {

			return new Promise(async (resolve, reject) => {
				let res = {
					data: {},
				};
				if (uni.getStorageSync("zegoToken")) {
					res.data.token = uni.getStorageSync("zegoToken");
					res.code = 1;
				} else {
					res = await loginApi.getzegotoken_chat({
						user_id: context.state.userInfo.id,
					});
				}
				if (res.code == 1) {
					console.log('zego', res.data.token)
					context.state.zim.login({
								userID: context.state.userInfo.id + "",
								userName: context.state.userInfo.nickname,
							},
							res.data.token
						)
						.then(function() {
							console.log('zim头像准备')
							try {
								let avatar = context.state.userInfo.is_server == 1 ? context
									.state.userInfo.service_info.logo : context.state.userInfo
									.avatar
								let userName = context.state.userInfo.is_server == 1 ? context
									.state.userInfo.service_info.name : context.state.userInfo
									.nickname
								if (userName)
									context.state.zim.updateUserName(userName)
								if (avatar)
									context.state.zim.updateUserAvatarUrl(avatar).then(
										function({
											userAvatarUrl
										}) {
											// 操作成功
											console.log('换头像操作成功', userAvatarUrl)
										})
									.catch(function(err) {
										// 操作失败
										console.log('换头像操作失败')
									});
							} catch (error) {
								console.log(error)
							}
							console.log('zim头像成功')
							console.log('zim登录成功')
							context.dispatch('queryConversationList')
							resolve('登录成功')
						})
						.catch(function(err) {
							console.log('zim登陆失败')
							setTimeout(() => {
								uni.removeStorageSync("zegoToken");
								context.dispatch('ZIMLogin')
							}, 1500);
							context.state.zim.logout()
						});
				}

			})

		},

		queryConversationList(context) {
			if (context.state.zim)
				return new Promise(async (resolve, reject) => {
					context.state.zim
						.queryConversationList({
							// 会话锚点，传空则代表从最新开始查询
							nextConversation: null,
							count: 20
						})
						.then(function({
							conversationList
						}) {
							console.log('会话列表---', conversationList)
							let num = 0
							for (let item of conversationList) {
								num += item.unreadMessageCount
							}
								console.log('消息未读数', num)
							if (num > 0) {
								uni.showTabBarRedDot({
									index: 3
								})
							}else{
								uni.hideTabBarRedDot({
									index: 3
								})
							}
							// 查询成功，开发者需要保存和维护数组内的会话对象
							context.commit('set_conversationList', conversationList)
							
							resolve(conversationList)
						})
						.catch(function(err) {
							// 查询失败
							reject(err)
						});
				})

		},
	},
	getters: {

	},
	modules: {

	}

})

// 3. 导出store对象
export default store